package com.thexb.interceptor;

import com.alibaba.fastjson2.JSON;
import com.thexb.common.JwtUtil;
import com.thexb.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtInterceptoer implements HandlerInterceptor {
    @Autowired
    private JwtUtil coderJwt;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("X-Token");
        log.debug("检查token" + token);
        if (token == null) {
            return false;
        }
        try {
            coderJwt.parseToken(token);
            log.debug(request.getRequestURI() + "验证成功");
            return true;
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
        log.debug(request.getRequestURI() + "验证失败");

        // 设置返回数据
        response.setContentType("application/json;charset=utf-8");
        Result<Integer> r = Result.fail(null, "jwt无效，请重新登陆");
        response.getWriter().write(JSON.toJSONString(r));
        return false;
    }
}
